/**
 * 审批页面
 * 跳转时传入 {
 *   approveType:'业务类型', 
 *   dictKey:'业务key',
 *   backPage:'返回页面'
 * }
 */
import React, { Component } from 'react';
import {
	StyleSheet, Text, View, TouchableOpacity,
	PixelRatio, Image, FlatList
} from "react-native";
import { NavigationEvents } from 'react-navigation';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import { Common } from '../../../../component/common/Common.js';
import { PageStatusIndex } from '../../../../component/page-status/PageStatusIndex';
import { ApproveItemContainer } from './ApproveItemContainer';
import { Tabs } from '../_component/tabs';
import OrderApproveService from '../_common/service';
import StorageHelper from '../../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../../config/storage';
import { NewAccountHome } from '../../../../components/common/newAccountHome';
import { SlideSelect } from '../../../../components/common/slideSelect';
const scale = GLOBAL.SCALE;

export class ApproveListPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		const { params } = navigation.state;
		console.log(params)
		return {
			headerTitle: params.name || '全部审批',
			headerTintColor: style.color.white,
			headerLeft: <Common type="headLeft" onPress={() => { navigation.navigate('HomePage'); }} color='#fff' />,
			headerRight: (<Image style={style.head.headRightEmpty} source={require('../../../../imgs/goBackEmpty.png')} />),
			headerStyle: style.head.headerStyle,
			headerTitleStyle: {
				flex: 1,
				textAlign: 'center'
			}
		}
	};

	constructor(props) {
		super(props);

		if (this.props.navigation.state.params && this.props.navigation.state.params.pageUrl) {
			this.params = this.props.navigation.state.params;
		} else {
			this.params = { // 极光推送用
				approveType: "O",
				dictKey: "ORDER_APP_APPROVAL_TASK",
				formKey: "",
				formKeyNew: "SIGNED",
				name: "订单成交报告审批任务",
				pageUrl: "ApproveListPage"
			}
		}
		let { choice } = this.params || {};
		this.state = {
			tabIndex: 0,
			companyIndex: 0,
			newLotData: [],  // 待审批
			status: 'loading',
			loadIcon: false,  // 下拉涮新的 图标
			alertShow: false,
			options: [],
			choice: choice || {}
		}
		this.pageNo = 1;
		this.totalPage = 1;
	}

	async componentWillMount() {
		await this._getListData();
	}

	//获取业务组织
	// async  getSorage () {
	// 	const userInfoJson = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
	// 	const userInfo = JSON.parse(userInfoJson);
	// 	this.setState({
	// 		options: userInfo.corpInfoTOs || [],
	// 		choice: this.state.choice.corpId ? this.state.choice : userInfo.corpInfoTOs[0]
	// 	})
	// }

	//获取待审批,已审批列表
	async _getListData(agentObj) {
		let { tabIndex } = this.state;
		let sendData = {
			onrefresh: false,
			pageNo: 1,
			// corpId: this.state.choice.corpId
		}
		Object.assign(sendData, agentObj);
		this.setState({
			loadIcon: true
		})
		//跳转列表时，需传一个类型来源approveType   订单->O  付款申请->P  授信—>C  合同变更->A  长约变更->LC
		let responseDataAll = await OrderApproveService.getApproveList(this.params, tabIndex, sendData);
		let responseData = responseDataAll && responseDataAll[this.state.companyIndex] && responseDataAll[this.state.companyIndex].paginationModel
		let options = responseDataAll || [];
		options.map(item => {
			item.rowCount = item && item.paginationModel && item.paginationModel.recordCount
		})
		this.setState({
			options,
			choice: options[this.state.companyIndex] || {},
			loadIcon: false
		});

		if (responseData) {
			this.totalPage = responseData.totalPage;
			if (sendData.onrefresh) {  // 加载
				this.setState({
					newLotData: this.state.newLotData.concat(responseData.rows),
					status: 'data'
				})
			} else { // 刷新
				this.setState({
					newLotData: responseData.rows,
					status: responseData.rows && responseData.rows.length ? 'data' : 'empty'
				})
			}
		} else {
			this.setState({
				status: 'empty'
			})
		}
	}

	// 下拉更新函数
	_isLoadRefresh() {
		this._getListData();
	}

	//上啦加载
	_loadData() {
		if (this.totalPage > this.pageNo) {
			this.pageNo++;
			this._getListData({
				pageNo: this.pageNo,
				onrefresh: true
			});
		}
	}

	//tab 切换
	_tabs = (index) => {
		this.pageNo = 1;
		this.setState({
			tabIndex: index,
			status: 'loading',
			alertShow: false
		}, function () {
			this._getListData();
		})
	}

	//跳审批页面
	_goDetail = (paramsData, title, itemInfo) => {
		console.log('paramsData.resUrl', paramsData.resUrl)
		this.props.navigation.navigate(paramsData.resUrl, {
			paramsData,
			title,
			status: this.state.tabIndex ? 'HASLOT' : 'LOT',
			choice: this.state.choice,
			itemInfo
		})
	}

	//数据加载出错回调
	_onErrorPress = () => {
		this.setState({
			status: 'loading'
		}, function () {
			this._getListData();
		})
	}

	// 一条数据
	_renderItem(list) {
		return (
			<ApproveItemContainer
				itemInfo={list.item}
				approveType={this.params.approveType}
				dictKey={this.params.dictKey}
				choice={this.state.choice}
				goDetail={(paramsData, title) => {
					this._goDetail(paramsData, title, list.item);
				}} />
		)
	}

	_getSearchView() {
		/**
		 * 客户列表页隐藏头部，此处 搜索框和添加企业按钮作为头部展示
		 */
		return (
			<View style={styles.searchCell}>
				<TouchableOpacity style={styles.searchInputCell} activeOpacity={1} onPress={() => {
					const { navigate } = this.props.navigation;
					navigate('EnterpriseSearchPage', {
					});
				}}>
					<View style={styles.searchInput}>
						<Image source={searchPic} style={styles.searchPlaceholderPic} />
					</View>
				</TouchableOpacity>
				<TouchableOpacity style={styles.searchLeftCell} activeOpacity={1} onPress={() => {
					const { navigate } = this.props.navigation;
					navigate('EnterpriseCreateBaseInfo', { choice: this.state.choice });
				}}>
				</TouchableOpacity>
				<TouchableOpacity activeOpacity={1} onPress={() => {
					this.setState({
						filterModalVisible: true,
					});
				}}>
					<Text style={styles.filterText}>筛选</Text>
				</TouchableOpacity>
			</View>
		);
	}

	render() {
		let { tabIndex, companyName, newLotData, status, alertShow, choice, options } = this.state;
		// const searchView = this._getSearchView();
		return (
			<View style={styles.container}>
				{options.length > 1 ?
					<NewAccountHome
						fn={(val) => {
							this.setState({ companyIndex: val }, () => {
								this.pageNo = 1;
								this._getListData()
							})
						}}
						options={options}
						choice={choice} />
					: null}
				{/* <Tabs tabIndex={tabIndex} checkTab={(tab) => { this._tabs(tab); }} /> */}
				<NavigationEvents onWillFocus={async () => {
					// await this.getSorage();
					await this._getListData()
				}} onDidBlur={() => { this.pageNo = 1; }} />
				{/* {searchView} */}
				{
					status == 'data' ? (
						<View style={styles.listBox}>
							<FlatList
								data={newLotData}
								renderItem={this._renderItem.bind(this)}
								refreshing={this.state.loadIcon}
								onRefresh={this._isLoadRefresh.bind(this)}
								onEndReachedThreshold={1}
								onEndReached={() => { this._loadData() }}
							/>
						</View>
					) : null
				}
				<PageStatusIndex status={status} emptyText="暂无记录" onErrorPress={this._onErrorPress} />

				{/* <SlideSelect alertShow={alertShow} options={options}
					select={(val) => {
						this.setState({ choice: val || options[0], alertShow: false }, () => {
							this._isLoadRefresh();
						})
					}}
					unselect={() => {
						this.setState({ alertShow: false })
					}} /> */}
			</View >
		)
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		backgroundColor: style.color.white,
	},
	listItem: {
		width: '100%',
		paddingTop: 12 * scale,
		paddingBottom: 12 * scale,
		flexDirection: 'row',
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.gray,
	},
	leftImg: {
		width: 40 * scale,
		height: 40 * scale,
		marginLeft: 15 * scale
	},
	conent: {
		width: 265 * scale,
		paddingLeft: 15 * scale
	},
	rightText: {
		color: '#2F7BFF'
	},
	titleBox: {
		flexDirection: 'row',
		alignItems: 'center',
		marginBottom: 5 * scale
	},
	title: {
		fontSize: 14 * scale,
		color: '#222',

	},
	infoText: {
		fontSize: 12 * scale,
		color: '#8b8b8b'
	},
	elementImg: {
		width: 21 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale
	},
	listBox: {
		flex: 1,
		//paddingBottom: 40 * scale,
		backgroundColor: style.color.bgGray,
	},
	//列表item样式
	orderText: {
		fontSize: 12 * scale,
		color: '#8B8B8B'
	},
	orderVal: {
		fontSize: 12 * scale,
		color: '#000'
	},
	orderCol: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 25 * scale,
		width: 175.5 * scale,
	},
	orderMain: {
		flexDirection: 'row',
		paddingTop: 8 * scale,
		paddingBottom: 8 * scale,
		flexWrap: 'wrap'
	},
	orderHeadPic: {},
	orderHeadText: {
		fontSize: 14 * scale,
		color: '#222',
		marginRight: 6 * scale,
		marginLeft: 6 * scale,
		flexWrap: 'wrap',
		// width: '70%'

	},
	orderHeadLeft: {
		height: 44 * scale,
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderHead: {
		width: 351 * scale,
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		height: 44 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		flexDirection: 'row',
	},
	orderCell: {
		width: 375 * scale,
		backgroundColor: '#fff',
		alignItems: 'center',
		marginBottom: 12 * scale,
	},
	order: {
		width: 351 * scale,
	}, conImage: {
		width: 20 * scale,
		height: 14 * scale,
		marginLeft: 5 * scale,
	}, forwardText: {
		paddingTop: 2 * scale,
		marginTop: 2 * scale,
		marginLeft: 6 * scale,
		width: 30 * scale,
		height: 16 * scale,
		backgroundColor: '#49CAFF',
		color: '#FFFFFF',
		fontSize: 11 * scale,
		textAlign: 'center',
		borderRadius: 4 * scale,
	},
	statusText: {
		fontSize: 13 * scale,
		color: style.color.themeColor,
	},
	accountSelect: {
		backgroundColor: style.color.themeColor,
		flexDirection: 'row',
		alignItems: 'center',
		justifyContent: 'center'
	}
})